package com.justgame.project.cloud.common.util;

import org.apache.commons.beanutils.PropertyUtils;
import java.util.*;
import java.util.stream.Collectors;

public class BeanMapUtils {
    public static Map<String, Object> pick(Object o, String... properties) {
        if(Objects.isNull(o)){
            return new HashMap<>();
        }
        return pick(null, o, properties);
    }

    public static List<Map<String, Object>> pick(List<?> o, String... properties) {
        if (o == null) {
            return new ArrayList<>();
        }
        return o.stream().map(item -> pick(item, properties)).collect(Collectors.toList());
    }

    @SuppressWarnings("unchecked")
    private static Map<String, Object> pick(Map<String, Object> map, Object o, String... properties) {
        if (map == null) {
            map = new HashMap<>();
        }

        if (o == null) {
            return map;
        }

        for (String property : properties) {
            String key = property;

            String[] parts = property.split("\\.");
            boolean multiParts = parts.length > 1;
            if (multiParts) {
                key = parts[0];
            }

            Object value;
            try {
                value = PropertyUtils.getProperty(o, key);
            } catch (Exception e) {
                throw new RuntimeException(String.format("%s 类中属性 %s 时发生错误", o.getClass().getSimpleName(), key), e);
            }

            map.put(key, multiParts ? pick((Map<String, Object>) map.get(key), value, parts[1]) : value);
        }
        return map;
    }
}
